import React from 'react';
import $ from 'webpack-zepto';
import Config from '../../common/config.js';
import Util from '../../common/util.js';
import Loader from '../../common/loader.js';
import GoodsItem from '../../activity/componet/goods-item.js';

var scope;
var total = '0.00';
var toBuyGoods = [];
export default class CartList extends React.Component {
    constructor(props) {
        super(props);
        scope = this;
        scope.initCartStatus();
        scope.state = {
            data: props.data,
            isChecked: false,
            total: total
        };
    };

    initCartStatus() {
        scope.props.data.map(function (cart) {
            cart.isChecked = false;
            cart.isEdit = false;
        });
    };

    productList(obj) {
        return (
            <div className="box">
                {scope.boxLeft(obj)}
                {scope.boxEdit(obj)}
                {scope.boxEnd(obj)}
            </div>
        );
    };

    activityList(data) {
        var activityGoods = '';
        var activityShow=false;
        if(data.yhg_cart&&data.yhg_cart!=0){
            activityShow=true;
        }
        var goodsItem = "";
        //
        if (activityShow) {
            data.yhg_cart[0].goods_name = data.yhg_cart[0].gc_name;
            var settings = {
                goodsItem: data.yhg_cart[0],
                parent: data,
                isOpt: data.isEdit
            };

            return activityGoods = <GoodsItem settings={settings} type="cart" callbackParent={this.resetTotal}></GoodsItem>
        }

        return activityGoods
    }
    resetTotal(total,parent){
        if(parent.isChecked){
            scope.setState({
                total:parseFloat(scope.state.total)+total
            })
        }
    }
    boxLeft(obj) {
        return (
            <div className="boxLeft">
                <div className="circle"
                     onClick={scope.setCartStatus.bind(this,obj,'isChecked',function(cart){ return scope.checkedCallback(cart);})}>
                    <span className={"bg " + (obj.isChecked ? 'blue' : 'white')}></span>
                </div>
                <div className="product">
                    <a href={'goods-view.html?goods_common_id=' + obj.goods_common_id + '&appid=' + scope.props.appId}>
                        <img src={obj.goods_thumb}/>
                    </a>
                </div>
            </div>
        );
    };

    boxEdit(obj) {
        return (
            <div className={"boxEdit " + (obj.isEdit ? 'hidden' : 'show')}>
                <div className="goods-name">{Util.shortStr(obj.gc_name, 8, '...')}</div>
                <p>
                    <span>规格:</span>
                    <span>{obj.spec_desc}</span>
                </p>
                <p>
                    <span>RMB</span>
                    <span>{obj.sale_price}</span>
                    <span>起</span>
                </p>
                <a href="#" className="edit" onClick={scope.setCartStatus.bind(this,obj,'isEdit',function(cart){
                 return cart.isEdit ? false : true; })}>编辑</a>
            </div>
        );
    };

    boxEnd(obj) {
        return (
            <div className={"boxEnd " + (obj.isEdit ?  'show' : 'hidden')}>
                <p>数量：</p>
                <div className="numberSelect">
                    <span onClick={scope.setCartStatus.bind(this,obj,'goods_num',function(cart){
                       if(cart.yhg_cart&&cart.yhg_cart.length!=0&&cart.yhg_cart[0].goods_num>=cart.goods_num&&cart.goods_num!=1){
                          cart.yhg_cart[0].goods_num=cart.yhg_cart[0].goods_num-1;
                           $.ajax({
                              url: Config.path('duolu/cart', ['?uToken=' + Util.storage().get(scope.props.appId)]),
                              type: 'put',
                              data:  cart.yhg_cart[0],
                              success:function(resp){
                                 if(cart.isChecked){
                                 total = parseFloat(scope.state.total) - cart.yhg_cart[0].sale_price;
                                  scope.setState({total : total});
                                 }
                             }
                            });
                       };
                       if(cart.isChecked && cart.goods_num>1){
                           total = parseFloat(scope.state.total) - cart.sale_price;
                            scope.setState({total : total});
                       };
                          return cart.goods_num <= 1 ? 1 : --cart.goods_num;
                    })}></span>
                    <span>{obj.goods_num}</span>
                    <span onClick={scope.setCartStatus.bind(this,obj,'goods_num',function(cart){
                        if(cart.isChecked){
                            total = parseFloat(scope.state.total) + parseFloat(cart.sale_price);
                            scope.setState({total : total});
                        }
                        return ++cart.goods_num;
                    })}></span>
                </div>
                <div className="choose">
                    <a href="#" onClick={scope.deleteCart.bind(this,obj.cart_id)}>删除</a>

                    <a href="#" onClick={scope.setCartStatus.bind(this,obj,'isEdit',function(){
                        return false;
                    })}>完成</a>
                </div>
            </div>
        );
    };

    checkedCallback(cart) {
        var result = cart.isChecked ? false : true;
        total = parseFloat(total);
        if (result) {
            if (cart.yhg_cart&&cart.yhg_cart.length != 0) {
                total += parseFloat(cart.sale_price * cart.goods_num + cart.yhg_cart[0].sale_price * cart.yhg_cart[0].goods_num);
                scope.addToBuyGoods(cart);
            } else {
                total += parseFloat(cart.sale_price * cart.goods_num);
                console.log(total);
                scope.addToBuyGoods(cart);
            }
        } else {
            if (cart.yhg_cart&&cart.yhg_cart.length != 0) {
                
               total -= parseFloat(cart.sale_price * cart.goods_num + cart.yhg_cart[0].sale_price * cart.yhg_cart[0].goods_num);
                console.log(total);
                scope.deleteToBuyGoods(cart);
                if (total <= 0) {
                    total = 0;
                }
            } else {
                total -= parseFloat(cart.sale_price * cart.goods_num);
                scope.deleteToBuyGoods(cart);
                if (total <= 0) {
                    total = 0;
                }
            }

        }
        scope.setState({total: total.toFixed(2)});
        return result;
    };

    deleteCart(cart_id) {
        $.ajax({
            url: Config.path('duolu/cart', ['?uToken=' + Util.storage().get(scope.props.appId), '&cart_id=' + scope.getDeleteCartId(cart_id)]),
            type: 'delete',
            beforeSend: function () {
                Loader.start();
            },
            success: function (resp) {
                if (resp.status == 200) {
                    window.location.reload();
                } else if (resp.status == 401) {
                    window.location.href = 'index.html?appid=' + scope.props.appId;
                }
                Loader.end();
            }
        });
    };

    getDeleteCartId(ids) {
        var array = ids.split(',');
        var id = '';
        for (var i = 0; i < array.length; i++) {
            id += array[i];
            if (i != array.length - 1) {
                id += '_';
            }
        }
        return id;
    };

    setCartStatus(cart, key, callback) {
        var list = scope.state.data.map(function (_cart) {
            if (cart.goods_id == _cart.goods_id) {
                _cart[key] = callback.call(this, _cart);
                if (key == 'goods_num') {
                    $.ajax({
                        url: Config.path('duolu/cart', ['?uToken=' + Util.storage().get(scope.props.appId)]),
                        type: 'put',
                        data: _cart
                    });
                }
            }
            return _cart;
        });
        scope.setState({data: list});
    };

    cartBottom() {
        return (
            <div className="cartBottom">
                <div className="bottom-box">
                    <div className="selectBtn">
                        <div>
                            <span className={'checkAll ' + (scope.state.isChecked ? 'blue' : 'white')}
                                  onClick={scope.selectAll}></span>
                        </div>
                        <div><label>全选</label></div>
                        <div>
                            <span>共计：RMB</span><span className="cart-total">{scope.state.total}</span>
                        </div>
                    </div>
                    <div className="to-buy-btn" onClick={scope.toBuy}>立即购买</div>
                </div>
            </div>
        )
    };

    selectAll() {
        var isChecked = scope.state.isChecked;
        scope.state.data.map(function (cart) {
            scope.setCartStatus(cart, 'isChecked', function (cart) {
                if (isChecked) {
                    cart.isChecked = isChecked;
                    return scope.checkedCallback(cart);
                } else {
                    if (cart.isChecked) {
                        return cart.isChecked = true;
                    } else {
                        cart.isChecked = isChecked;
                        return scope.checkedCallback(cart);
                    }
                }
            });
        });
        scope.setState({isChecked: isChecked ? false : true});
    };

    render() {
        return (
            <div>
                <ul>
                    {scope.state.data.map(function (data, i) {
                        return (
                            <li key={i}>
                                {scope.productList(data)}
                                {scope.activityList(data)}
                            </li>
                        );
                    })}
                </ul>
                {this.cartBottom()}
            </div>
        );
    };

    toBuy() {
        if (toBuyGoods.length == 0) {
            return;
        }

        if (!scope.isEditStatus()) {
            return;
        } else {

            for(let i in toBuyGoods){
                let goods = toBuyGoods[i];
                if(goods.yhg_cart && goods.yhg_cart.length > 0){
                    goods.yhg_goods = [];
                    for(let i in goods.yhg_cart){
                        let activityGoods = goods.yhg_cart[i];
                        goods.yhg_goods.push({
                            gc_thumb : activityGoods.goods_thumb,
                            goods_name : activityGoods.goods_name,
                            gc_name : activityGoods.gc_name,
                            spec_desc : activityGoods.spec_desc,
                            add_price : activityGoods.sale_price,
                            yhg_goods_num : activityGoods.goods_num,
                            yhg_goods_id : activityGoods.goods_id
                        });
                    }
                }
            }

            Util.storage().put('toBuyGoods', {
                orderGoods: toBuyGoods,
                totalPrice: total
            });

            window.location.href = 'order.html?type=buy&appid=' + scope.props.appId;
        }
    };

    isEditStatus() {
        var cartList = scope.state.data;
        for (var i in cartList) {
            if (true == cartList[i].isEdit) {
                return false;
            }
        }

        return true;
    };

    addToBuyGoods(cart) {
        toBuyGoods.push(cart);
    };

    deleteToBuyGoods(cart) {
        var array = [];
        toBuyGoods.map(function (_cart) {
            if (_cart.goods_id != cart.goods_id) {
                array.push(_cart);
            }
        });
        toBuyGoods = array;
    };
}